package com.you.mybatis.base.util;

import java.io.IOException;
import java.io.InputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 *<p>
 *SqlSessionFactoryUtil
 *</p>
 *
 * @author liuyang
 * @date 2018-12-03 Mon 10:45:24
 * @since 1.0.0
 */
@Slf4j
public class SqlSessionFactoryUtil {

    private static SqlSessionFactory sqlSessionFactory = null;
    private static final String MYBATIS_CONFIG_LOCATION = "mybatis/mybatis-config.xml";

    private volatile static Object lock = new Object();

    private SqlSessionFactoryUtil() {
    }

    public static SqlSessionFactory getSqlSessionFactoryInstance() {
        return getSqlSessionFactoryInstance(MYBATIS_CONFIG_LOCATION);
    }

    /**
     *获取SqlSessionFactory单例
     *
     * @author liuyang
     * @date 2018-12-03 Mon 11:10:13
     * @param resource mybatis配置文件相对classpath位置
     * @return SqlSessionFactory
     */
    @SuppressWarnings("all")
    private static SqlSessionFactory getSqlSessionFactoryInstance(String resource) {
        InputStream inputStream = null;

        try {
            //双重锁
            //volatile与final无法同时声明，同步块锁的是对象的空间，不是引用，
            // 不要在同步块里对锁进行new操作，否则多线程竞争条件下造成锁失效
            if (sqlSessionFactory == null) {
                synchronized (lock) {
                    if (sqlSessionFactory == null) {
                        inputStream = Resources.getResourceAsStream(resource);
                        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                    }
                }
            }
        } catch (IOException e) {
            log.error("获取sqlSessionFactory异常, 请检查配置文件位置是否正确，", e);
        } finally {
            CloseUtil.close(inputStream);
        }

        return sqlSessionFactory;
    }

    public static SqlSession openSqlSession() {
        return openSqlSession(null);
    }

    /**
     *获取SqlSession
     *
     * @author liuyang
     * @date 2018-12-03 Mon 11:16:20
     * @param resource 配置文件位置
     * @return SqlSession
     */
    public static SqlSession openSqlSession(String resource) {
        if (sqlSessionFactory != null) {
            return sqlSessionFactory.openSession();
        }

        if (StringUtils.isEmpty(resource)) {
            sqlSessionFactory = getSqlSessionFactoryInstance();
        } else {
            sqlSessionFactory = getSqlSessionFactoryInstance(resource);
        }
        return sqlSessionFactory.openSession();
    }
}
